<?php
/**
 * @author spenceryg
 * @date 2022/4/14
 * @time 3:15 下午
 * @focus love & life
 */


namespace app\common\lib\verify;


use app\common\lib\verify\interfaces\Verify;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;

class TencentSmsVerify implements Verify
{
    protected $client = null;
    protected $template = null;

    public function sendCode(string $to, $code)
    {
        $code = is_array($code) ? $code : [$code];
        $to = ['+86' . $to];
        $req = new SendSmsRequest();
        $req->SmsSdkAppId = config('sms.tencent_sms.template.' . $this->template . '.SmsSdkAppId');
        $req->SignName = config('sms.tencent_sms.template.' . $this->template . '.SignName');
        $req->TemplateId = config('sms.tencent_sms.template.' . $this->template . '.TemplateId');
        $req->PhoneNumberSet = $to;
        $req->TemplateParamSet = $code;
        try{
            $this->client->SendSms($req);
        }catch (TencentCloudSDKException $e) {
            throw new \Exception($e->getMessage());
        }


    }

    public function __construct(string $template = 'default')
    {
        $this->template = $template;
        $cred = new Credential(config("sms.tencent_sms.SecretId"), config("sms.tencent_sms.SecretKey"));
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        $httpProfile = new HttpProfile();
        // 配置代理（无需要直接忽略）
        // $httpProfile->setProxy("https://ip:port");
        $httpProfile->setReqMethod("GET");  // post请求(默认为post请求)
        $httpProfile->setReqTimeout(30);    // 请求超时时间，单位为秒(默认60秒)
        $httpProfile->setEndpoint("sms.tencentcloudapi.com");  // 指定接入地域域名(默认就近接入)

        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        $clientProfile = new ClientProfile();
        $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法(默认为HmacSHA256)
        $clientProfile->setHttpProfile($httpProfile);

        // 实例化要请求产品(以sms为例)的client对象,clientProfile是可选的
        // 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);

        $this->client = $client;
    }
}
